from typing import TYPE_CHECKING

from PySide6.QtCore import QRect
from PySide6.QtGui import Qt, QPainter, QFont, QPen

from gui.reference import LW, Pos
from gui.signals import SIGNALS
from utils.event_bus import EVENT_BUS
from utils.reference import message_box_information

if TYPE_CHECKING:
    from common.world import LatticeMap
    from common.player.reference import Player


class Build:
    name = None

    @property
    def class_name(self):
        return self.__class__.__name__

    def __repr__(self):
        return f'Build<{self.name}>'

    def draw(self, painter: QPainter, pos: Pos):
        x, y = pos.to_xy()
        painter.save()
        painter.setPen(QPen(Qt.GlobalColor.black, 2))
        small_rect = QRect(x + 2, y + 2, LW - 4, LW - 4)
        painter.drawRect(small_rect)
        font = QFont()
        font.setFamily('SimHei')
        font.setPointSize(10)
        painter.setFont(font)
        painter.drawText(small_rect, Qt.AlignmentFlag.AlignCenter, self.name)
        painter.restore()

    def interaction(self, player: 'Player'):
        pass


class Portal(Build):
    name = '传送门'

    def __init__(self, aliases: str, identifier: str):
        self.aliases = aliases
        self.identifier = identifier
        self.map_name = None
        self.pos = None
        self.link = None

    def draw(self, painter: QPainter, pos: Pos):
        x, y = pos.to_xy()
        painter.save()
        painter.setPen(Qt.GlobalColor.blue)
        painter.drawEllipse(x + 1, y + 1, LW - 2, LW - 2)
        painter.setPen(Qt.GlobalColor.black)
        font = QFont()
        font.setFamily('SimHei')
        font.setPointSize(10)
        painter.setFont(font)
        painter.drawText(x, y, LW, LW, Qt.AlignmentFlag.AlignCenter, self.aliases)
        painter.restore()

    def interaction(self, player: 'Player'):
        lattice_map: "LatticeMap" = player.get_local_map()
        p_from: Portal = lattice_map.get_build(player.pos)
        if self.link:
            p_to: Portal = self.link.another(p_from)
            player.transfer_map(p_to.map_name)
            player.pos = p_to.pos
            SIGNALS.send_message.emit(f'地图移动: <span style="color:blue">{lattice_map.name}</span>')
            EVENT_BUS.player_interaction.emit(player)
        else:
            message_box_information('该地图未实现')


class LinkPortal:
    def __init__(self, p1: Portal, p2: Portal):
        self.left = p1
        self.right = p2

    def another(self, p: Portal):
        if p.identifier == self.left.identifier:
            return self.right
        elif p.identifier == self.right.identifier:
            return self.left
        else:
            return None


class TransferAltar(Build):
    """将装备的所有附加属性传承给另一件装备"""
    name = "传承祭坛"

    def __init__(self):
        self.left_solt = None
        self.right_solt = None
        self.raw_material: list[(str, int)] = []

    def check_material(self):
        return not self.raw_material or True
